<template>
  <div>
    <div class="goods">
      <div
        class="menu-wrapper"
        ref="menuwrapper"
      >
        <ul>
          <li
            v-for="(item, index) in goods"
            :key="item.name"
            @click="selectMenu($event, index)"
            class="menu-item"
            :class="{'current':currentIndex === index}"
          >
            <span class="text border-1px">
              <support-ico
                v-if="item.type>0"
                class="icon"
                :size="3"
                :type="item.type"
              ></support-ico>
              {{item.name}}
            </span>
          </li>
        </ul>
      </div>
      <div
        class="foods-wrapper"
        ref="foodswrapper"
      >
        <ul>
          <li
            v-for="item in goods"
            :key="item.food"
            class="food-list food-list-hook"
          >
            <h1 class="title">{{item.name}}</h1>
            <ul>
              <li
                @click="selectFood(food,$event)"
                v-for="food in item.foods"
                :key="food.name"
                class="food-item  border-1px"
              >
                <div class="icon">
                  <img :src="food.icon">
                </div>
                <div class="content">
                  <h2 class="name">{{food.name}}</h2>
                  <p class="desc">{{food.description}}</p>
                  <div class="extra">
                    <span class="count">月售{{food.sellCount}}份</span>
                    <span>好评率{{food.rating}}%</span>
                  </div>
                  <div class="price">
                    <span class="now"><span class="price-icon">￥</span>{{food.price}}</span>
                    <span
                      class="old"
                      v-show="food.oldPrice"
                    >￥{{food.oldPrice}}</span>
                  </div>
                  <div
                    class="cartcontrol-wrapper"
                    @click.stop
                    @click.prevent
                  >
                    <cartcontrol
                      :food="food"
                      @cart-add="cartAdd"
                    ></cartcontrol>
                  </div>
                </div>
              </li>
            </ul>
          </li>
        </ul>
      </div>
      <shopcart
        ref="shopcart"
        :selectfoods="selectFoods"
        :deliveryprice="seller.deliveryPrice"
        :minprice="seller.minPrice"
      ></shopcart>
    </div>
    <food
      ref="food"
      :food="selectedFood"
      @cart-add="cartAdd"
    ></food>
  </div>
</template>

<script>
import BScroll from 'better-scroll'
import shopcart from '../shopcart/shopcart'
import cartcontrol from '../cartcontrol/cartcontrol'
import supportico from '../support-ico/support-ico'
import food from '../food/food'

const ERR_OK = 0

export default {
  props: {
    seller: {
      type: Object
    }
  },
  data() {
    return {
      goods: [],
      listHeight: [],
      currentIndex: 0,
      scrollY: 0,
      selectedFood: {}
    }
  },
  computed: {
    selectFoods() {
      let foods = []
      this.goods.forEach((good) => {
        good.foods.forEach((food) => {
          if (food.count) {
            foods.push(food)
          }
        })
      })
      return foods
    }
  },
  created() {
    this.$http.get('api/goods').then((response) => {
      response = response.body
      if (response.errno === ERR_OK) {
        this.goods = response.data
        this.$nextTick(() => {
          this._initScroll()
          // this._calculateHeight()
        })
      }
    })
  },
  methods: {
    selectMenu(event, index) {
      if (!event._constructed) {
        return false
      }
      this.currentIndex = index
      this.move = true
      let foodList = this.$refs.foodswrapper.getElementsByClassName('food-list-hook')
      this.foodsScroll.scrollToElement(foodList[index], 300)
      setTimeout(() => {
        this.move = false
      }, 400)
    },
    selectFood(food, event) {
      if (!event._constructed) {
        return false
      }
      this.selectedFood = food
      this.$refs['food'].show()
    },
    cartAdd(el) {
      // this.$nextTick()函数代表dom元素更新后执行， 因此此处能正确打印出更改之后的值
      // 体验优化，异步执行下落动画
      this.$nextTick(() => {
        // 调用shopcart组件的drop()函数
        this.$refs['shopcart'].drop(el)
      })
    },
    _initScroll() {
      this.menuScroll = new BScroll(this.$refs.menuwrapper, {
        click: true
      })
      this.foodsScroll = new BScroll(this.$refs.foodswrapper, {
        click: true,
        // 这个属性的作用是让Scroll在滚动的时候实时地传递给我们滚动的位置，相当于探针的效果
        probeType: 3
      })
      // 通过foodsScroll对象监听一个scroll事件，
      // 后边这个事件的回调函数的参数pos就是当前位置
      this.foodsScroll.on('scroll', (pos) => {
        // 用在data里边定义的scrollY来接收pos.y
        // 因为它是小数，所以需要用到Math.round()
        this.scrollY = Math.round(pos.y)
      })
    },
    _calculateHeight() {
      let foodList = this.$refs.foodswrapper.getElementsByClassName('food-list-hook')
      let height = 0
      // 这里是先push第一个高度
      this.listHeight.push(height)
      // 遍历foodList这个类数组
      for (let i = 0; i < foodList.length; i++) {
        let item = foodList[i]
        // 通过DOM的clientHeight的接口拿到每一个foodList[i]的高度
        height += item.clientHeight
        // listHeight其实是一个递增的区间数组，标识了每一个区间距离顶部的高度
        this.listHeight.push(height)
      }
    }
  },
  watch: {
    goods() {
      setTimeout(() => {
        this._calculateHeight()
      }, 20)
    },
    scrollY(newY) {
      if (this.move) {
        return
      }
      const listHeight = this.listHeight
      if (newY > 0) {
        this.currentIndex = 0
        return
      }
      for (let i = 0; i < listHeight.length - 1; i++) {
        // 获得当前索引值的高度
        let height1 = listHeight[i]
        // 获得下一个索引值的高度
        let height2 = listHeight[i + 1]
        // 判断scrollY落到的区间是最后一个
        // 就返回当前的索引值
        if ((-newY >= height1 && -newY < height2)) {
          this.currentIndex = i
          return
        }
        this.currentIndex = listHeight.length - 2
      }
    }
  },
  components: {
    shopcart,
    cartcontrol,
    'support-ico': supportico,
    food
  }
}

</script>

<style lang='stylus' scoped>
@import '~common/stylus/mixin.styl'

.goods
  display: flex
  position: absolute
  width: 100%
  top: 174px
  bottom: 46px
  overflow: hidden
  .menu-wrapper
    flex: 0 0 80px
    width: 80px
    background: #f3f5f7
    .menu-item
      display: table
      padding: 0 12px
      width: 56px
      height: 54px
      line-height: 14px
      &.current
        position: relative
        z-index: 10
        margin-top: -1px
        font-weight: 700
        background: #fff
        .text
          border-none()
      .icon
        supports-icon('3')
      .text
        display: table-cell
        width: 56px
        vertical-align: middle
        font-size: 12px
        font-weight: 200
        border-1px(rgba(7, 17, 27, 0.1))
  .foods-wrapper
    flex: 1
    // overflow: auto
    .title
      padding-left: 14px
      height: 26px
      line-height: 26px
      border-left: 2px solid #d9dde1
      font-size: 12px
      color: rgb(147, 153, 159)
      background: #f3f5f7
    .food-item
      display: flex
      margin: 18px
      padding-bottom: 18px
      border-1px(rgba(7, 17, 27, 0.1))
      &:last-child
        border-none()
        margin-bottom: 0
      .icon
        flex: 0 0 57px
        margin-right: 10px
        img
          width: 57px
          height: 57px
          border-radius: 2px
      .content
        flex: 1
        .name
          margin: 2px 0 8px 0
          height: 14px
          line-height: 14px
          font-size: 14px
          color: rgb(7, 17, 27)
        .desc, .extra
          font-size: 10px
          color: rgb(147, 153, 159)
        .desc
          line-height: 12px
          margin-bottom: 8px
        .extra
          line-height: 10px
          .count
            margin-right: 12px
        .price
          line-height: 24px
          font-weight: 700
          .now
            margin-right: 8px
            font-size: 14px
            font-weight: 700
            color: rgb(240, 20, 20)
            .price-icon
              font-size: 10px
              font-weight: normal
          .old
            text-decoration: line-through
            font-size: 10px
            color: rgb(147, 153, 159)
        .cartcontrol-wrapper
          position: absolute
          right: 0
          bottom: 12px
</style>
